package com.yufubao.service.service.applet.product.impl;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.yufubao.framework.util.CopyBean;
import com.yufubao.framework.util.page.Query;
import com.yufubao.framework.result.PageUtils;
import com.yufubao.framework.enums.AttrType;
import com.yufubao.model.pojo.applet.product.AttrAttrgroupRelationEntity;
import com.yufubao.model.pojo.applet.product.AttrEntity;
import com.yufubao.model.pojo.applet.product.AttrGroupEntity;
import com.yufubao.model.vo.applet.product.AttrAttrGroupRelationVo;
import com.yufubao.model.vo.applet.product.AttrVo;
import com.yufubao.model.vo.applet.product.ClassifyTheAssociatedGroupingAndGroupingAttributesVo;
import com.yufubao.service.mapper.applet.product.AttrGroupDao;
import com.yufubao.service.service.applet.product.AttrAttrgroupRelationService;
import com.yufubao.service.service.applet.product.AttrGroupService;
import com.yufubao.service.service.applet.product.AttrService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.stream.Collectors;


@Service("appletAttrGroupService")
public class AttrGroupServiceImpl extends ServiceImpl<AttrGroupDao, AttrGroupEntity> implements AttrGroupService {

    @Autowired
    private AttrAttrgroupRelationService attrAttrgroupRelationService;

    @Autowired
    private AttrService attrService;


    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        IPage<AttrGroupEntity> page = this.page(
                new Query<AttrGroupEntity>().getPage(params),
                new QueryWrapper<AttrGroupEntity>()
        );

        return new PageUtils(page);
    }

    /**
     * @param params
     * @param catelogId
     * @return com.yufubao.common.result.PageUtils
     * @description 查詢所有分類的屬性分組
     * @author zhangyiheng
     * @date 2024/8/28 22:16
     */
    @Override
    public PageUtils queryPage(Map<String, Object> params, Integer catelogId) {
        PageUtils pageUtils = null;
        String key = (String) params.get("key");
        //默认catelogId等于0 查询所有

        if (StrUtil.isNotBlank(key)) {
            IPage<AttrGroupEntity> page = this.page(
                    new Query<AttrGroupEntity>().getPage(params),
                    Wrappers.<AttrGroupEntity>lambdaQuery()
                            .eq(StrUtil.isNotBlank(key), AttrGroupEntity::getCatelogId, key).or()
                            .eq(StrUtil.isNotBlank(key), AttrGroupEntity::getAttrGroupId, key)
                            .or().like(StrUtil.isNotBlank(key), AttrGroupEntity::getAttrGroupName, key)
            );
            pageUtils = new PageUtils(page);
            return pageUtils;
        }

        if (!Objects.isNull(catelogId)) {
            pageUtils = new PageUtils(this.page(
                    new Query<AttrGroupEntity>().getPage(params),
                    Wrappers.<AttrGroupEntity>lambdaQuery()
                            .eq(catelogId != 0, AttrGroupEntity::getCatelogId, catelogId)
            ));
        }
        return pageUtils;
    }

    /**
     * @param attrGroupId
     * @return java.util.List<com.yufubao.model.vo.cms.AttrVo>
     * @description 查询属性组下的属性
     * @author zhangyiheng
     * @date 2024/8/29 14:18
     */
    @Override
    public List<AttrVo> attrRelation(Long attrGroupId) {
        List<Long> attrIds = attrAttrgroupRelationService.list(Wrappers.<AttrAttrgroupRelationEntity>lambdaQuery().eq(AttrAttrgroupRelationEntity::getAttrGroupId, attrGroupId))
                .stream().map(AttrAttrgroupRelationEntity::getAttrId).collect(Collectors.toList());

        List<AttrEntity> attrEntities = null;
        if (CollUtil.isNotEmpty(attrIds)) {
            attrEntities = attrService.getBaseMapper().selectBatchIds(attrIds);
        }


        if (!Objects.isNull(attrEntities)) {
            return CopyBean.copyBeanList(attrEntities, AttrVo.class);
        }

        return null;
    }

    /**
     * @param vos
     * @return void
     * @description 删除关联属性
     * @author zhangyiheng
     * @date 2024/8/29 14:27
     */
    @Transactional
    @Override
    public void attrRelationDelete(List<AttrAttrGroupRelationVo> vos) {

        attrAttrgroupRelationService.attrRelationDelete(vos);
    }

    /**
     * @param params
     * @param attrGroupId
     * @return com.yufubao.common.result.PageUtils
     * @description 获取属性分组没有关联的其他属性
     * @author zhangyiheng
     * @date 2024/8/29 14:33
     */
    @Override
    public PageUtils noattrRelation(Map<String, Object> params, Long attrGroupId) {
        //查询中间表对应的数据，如果对应的查询不出那就查询不对应的
        List<AttrAttrgroupRelationEntity> relations = attrAttrgroupRelationService.list(Wrappers.<AttrAttrgroupRelationEntity>lambdaQuery()
                .eq(AttrAttrgroupRelationEntity::getAttrGroupId, attrGroupId).or()
                .ne(AttrAttrgroupRelationEntity::getAttrGroupId, attrGroupId));

        //获取分类id
        Long catelogId = this.getOne(Wrappers.<AttrGroupEntity>lambdaQuery()
                .eq(AttrGroupEntity::getAttrGroupId, attrGroupId)).getCatelogId();

        LambdaQueryWrapper<AttrEntity> wrapper = new LambdaQueryWrapper<>();

        //从中间库查询出的对应的属性id或者不对应的属性id
        List<Long> attrIds = relations.stream().map(AttrAttrgroupRelationEntity::getAttrId).collect(Collectors.toList());

        //如果属性id对应那就剔除不对应的有关联的属性id
        if (CollUtil.isNotEmpty(relations)) {


            //剔除不对应的 已经被绑定的属性id
            List<AttrAttrgroupRelationEntity> relations2 = attrAttrgroupRelationService.list(Wrappers.<AttrAttrgroupRelationEntity>lambdaQuery()
                    .notIn(AttrAttrgroupRelationEntity::getAttrId, attrIds));

            if (CollUtil.isNotEmpty(relations2)) {
                List<Long> attrIds2 = relations2.stream().map(AttrAttrgroupRelationEntity::getAttrId).collect(Collectors.toList());

                wrapper.notIn(AttrEntity::getAttrId, attrIds2);
            }
        }
        //如果从中间库查询出的属性id说明自身的这个属性分组没有绑定任何属性 就直接notin剔除已经绑定的属性id，如果中间库是空标识属性分组和属性没有对应关系就直接查询所有的
        wrapper.eq(AttrEntity::getCatelogId, catelogId).eq(AttrEntity::getAttrType, AttrType.BASE_TYPE.getCode()).notIn(CollUtil.isNotEmpty(attrIds), AttrEntity::getAttrId, attrIds);

        IPage<AttrEntity> page = attrService.page(
                new Query<AttrEntity>().getPage(params),
                wrapper
        );

        return new PageUtils(page);
    }

    /**
     * @param vos
     * @return void
     * @description 添加属性与分组关联关系
     * @author zhangyiheng
     * @date 2024/8/29 14:37
     */
    @Override
    public void attrRelationS(List<AttrAttrGroupRelationVo> vos) {
        attrAttrgroupRelationService.saveBatch(vos);
    }

    /**
     * @param catelogId
     * @return java.lang.Object
     * @description 获取分类下所有分组&关联属性
     * @author zhangyiheng
     * @date 2024/8/29 14:54
     */
    @Override
    public List<ClassifyTheAssociatedGroupingAndGroupingAttributesVo> getClassifyTheAssociatedGroupingAndGroupingAttributes(Long catelogId) {

        //获取当前分类下的所有分组
        List<AttrGroupEntity> groups = this.list(Wrappers.<AttrGroupEntity>lambdaQuery().eq(AttrGroupEntity::getCatelogId, catelogId));

        //根据分组查询属性
        if (CollUtil.isNotEmpty(groups)) {

            List<ClassifyTheAssociatedGroupingAndGroupingAttributesVo> vos = groups.stream().map(po -> {
                ClassifyTheAssociatedGroupingAndGroupingAttributesVo vo = CopyBean.copyBean(po, ClassifyTheAssociatedGroupingAndGroupingAttributesVo.class);
                List<AttrAttrgroupRelationEntity> relations = attrAttrgroupRelationService.list(Wrappers.<AttrAttrgroupRelationEntity>lambdaQuery()
                        .eq(AttrAttrgroupRelationEntity::getAttrGroupId, vo.getAttrGroupId()));


                if (CollUtil.isNotEmpty(relations)) {
                    List<AttrEntity> attrs = attrService.list(Wrappers.<AttrEntity>lambdaQuery()
                            .in(AttrEntity::getAttrId, relations.stream().map(AttrAttrgroupRelationEntity::getAttrId).collect(Collectors.toList())));
                    vo.setAttrs(attrs);
                }

                return vo;
            }).collect(Collectors.toList());

            return vos.stream().filter(po -> {
                if (CollUtil.isEmpty(po.getAttrs())) {
                    return false;
                } else {
                    for (AttrEntity attr : po.getAttrs()) {
                        if (attr.getAttrType().equals(AttrType.SALE_TYPE.getCode())) {
                            return false;
                        }
                    }
                }
                return true;
            }).collect(Collectors.toList());

        }

        return null;
    }
}